/**
 * Dear programmer:
 * When I wrote this code, only god and I knew how it worked.
 * Now, only god knows it!
 *
 * @author: Pegasus  Date: 2018/11/21 Time: 10:03
 *
 * 工作
 */

import React, {Component} from 'react';
import {
    SafeAreaView,
    View,
    Text,
    Image,
    ScrollView,
    TouchableOpacity,
    TouchableHighlight, Platform, BackHandler, ToastAndroid, FlatList, Modal
} from 'react-native';
import {connect} from 'react-redux';
import {styles} from './allOrderScreen.Style';
import OffWorkView from "../../../component/OffWorkView/OffWorkView"
import {RetrieveRoomsViewAs,HoReservationDefault,orderSweepSave} from "./Actions";
import {FetchStatus} from "../../../configuration/RequestConfiguration";
import {ReturnStatus} from "../../../configuration/ReturnStatus";
import {doDisplayWarnMessage} from "../../../component/Message/Action";
import AntDesign from "react-native-vector-icons/AntDesign";
import Feather from "react-native-vector-icons/Feather";
import FontAwesome from "react-native-vector-icons/FontAwesome";
import LoadingView from "../../../component/LoadingView/LoadingView";
import User from "../../../model/User/User";
import {SCREEN_WIDTH} from "../../../constant/PHScreen";
import {COLOR_GRAY_LINE, FONT_COLOR_TITLE} from "../../../constant/PHColors"

class allOrderScreen extends Component {

    static navigationOptions = ({navigation}) => ({
        headerTitle: ``,
        headerLeft: <View><Text style={{marginLeft:15,fontSize:18,color:FONT_COLOR_TITLE}}>房态盘</Text></View>,
        headerRight: <OffWorkView navigation={navigation}/>
    });

    // 构造
    constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            multiCheck:false,           //是否多选
            multiCheckRooms:{},           //多选选中房间
            RoomsViewArr_og:[],
            RoomsViewArr:[],
            ftpnoico:[],        //记录房态盘不显示图标合集
            roomSearchStr:{"wherestatus":{"All":"1"},"arg":{"arg":"房务"},"where":{"building":"","rmtype":"","floor":"","allSearch":"","source":"","market":"","features":"","grno":""}},//搜索条件
            floor:"-1", //初始化楼层分类
            ftpnoicoArr:[],
            selectValue:{"roomService_c":"所有房间"},
            searchText:"查询条件",
            INHouse:0, //在住数量
            refreshing:false,
            moreOperateModal:false,
            showCleanRoom:true,             //显示干净房
        };
    }

    componentWillReceiveProps(nextProps, nextContext): void {
        let {dispatch} = this.props;
        if (nextProps.onRetrieveRoomsView !== this.props.onRetrieveRoomsView && nextProps.onRetrieveRoomsView.fetchStatus === FetchStatus.Success) {
            if (nextProps.onRetrieveRoomsView.RETURN === ReturnStatus.Success) {
                let RoomsViewArr = nextProps.onRetrieveRoomsView.DATA;
                let INHouse = 0;

                RoomsViewArr.map((item,index)=>{
                    if(item.INHouse==="1"){
                        INHouse = INHouse+1;
                    }
                })

                this.setState({
                    RoomsViewArr_og:RoomsViewArr,
                    RoomsViewArr: RoomsViewArr,
                    INHouse: INHouse,
                    refreshing:false,
                });
                // console.log(RoomsViewArr)

            } else {
                dispatch(doDisplayWarnMessage(nextProps.onRetrieveRoomsView.MSG))
            }
        }

        if (nextProps.onReservationDefault !== this.props.onReservationDefault && nextProps.onReservationDefault.fetchStatus === FetchStatus.Success) {
            if (nextProps.onReservationDefault.RETURN === ReturnStatus.Success) {
                let ftpnoico = nextProps.onReservationDefault.ftpnoico.toLocaleLowerCase().split(",");
                this.setState({
                    ftpnoicoArr: ftpnoico,
                });
                // console.log("------------------"+ftpnoico)

            } else {
                dispatch(doDisplayWarnMessage(nextProps.onReservationDefault.MSG))
            }
        }

        //领取任务
        if (nextProps.onOrderSweepSave !== this.props.onOrderSweepSave && nextProps.onOrderSweepSave.fetchStatus === FetchStatus.Success) {
            if (nextProps.onOrderSweepSave.RETURN === ReturnStatus.Success) {
                this.setState({
                    multiCheckRooms:{},
                    multiCheck:false,
                });
                let str = this.state.roomSearchStr;
                dispatch(RetrieveRoomsViewAs(JSON.stringify(str)));
            } else {
                dispatch(doDisplayWarnMessage(nextProps.onOrderSweepSave.MSG))
            }
        }
    }

    // 组件渲染后调用
    componentDidMount() {
        // this.props.navigation.navigate('MainNavigator');
        let {dispatch} = this.props;
        let param = {"arg":{"arg":"初始化","filed":""},"ho_guest":{"arr_d":"","nights":"","exp_dep_d":"","adults":"","form-field-radio":"on","market":"","source":"","pno":"","comp_id":"","m_cardno":"","rcode":""},"ho_profile":{"pno":""}};
        dispatch(HoReservationDefault(JSON.stringify(param)));
        let str = this.state.roomSearchStr;
        dispatch(RetrieveRoomsViewAs(JSON.stringify(str)));
    }

    render() {
        let {dispatch,onRetrieveRoomsView} = this.props;

        if (this.state.RoomsViewArr_og.length===0) {
            return <LoadingView/>
        }else{
            return (
                <SafeAreaView style={styles.container}>
                    {
                        this.searchTitle()
                    }
                    <FlatList
                        data = {[""]}
                        onRefresh = {this._onRefresh.bind(this)} //刷新操作
                        refreshing = {this.state.refreshing}
                        renderItem={this._renderItem}
                        ListFooterComponent={this._renderFooter()}
                        onEndReachedThreshold={0.1}
                        keyExtractor={(item, index) => index.toString()}
                        onEndReached={this._onEndReached()}
                    />
                    {
                        (this.state.multiCheck) && (this.multiBtn())
                    }

                    {/*确认模态*/}
                    <Modal visible={this.state.moreOperateModal} animationType = {'none'} transparent = {true} onRequestClose={()=> this.onRequestClose()} >
                        <TouchableOpacity style={{flex: 1}} activeOpacity={1}  onPress={()=>{
                            this.onRequestClose();
                        }}>
                            <View style={styles.checkmodalContainer} >
                                <View style={styles.checkModalBody}>
                                    <TouchableOpacity activeOpacity={1} onPress={()=>{
                                        this.state.showCleanRoom = !this.state.showCleanRoom;
                                        this.changeRoomsViewArr()
                                    }}>
                                        <View style={styles.checkModalLine}>
                                            {
                                                (this.state.showCleanRoom)
                                                    ?
                                                    (
                                                        <Image style={{width: 18, height: 18}} source={require('../../../resource/login/dl_yixuan.png')}/>
                                                    )
                                                    :
                                                    (
                                                        <Image style={{width: 18, height: 18}} source={require('../../../resource/login/dl_weixuan.png')}/>
                                                    )
                                            }
                                            <Text style={{fontSize: 16}}>
                                                显示干净房
                                            </Text>
                                        </View>
                                    </TouchableOpacity>
                                </View>
                            </View>
                        </TouchableOpacity>
                    </Modal>
                </SafeAreaView>
            )
        }

    }

    changeRoomsViewArr(){
        let RoomsViewArr = [];
        this.state.RoomsViewArr_og.map((item,index)=>{
            if(this.state.showCleanRoom===false && (item.hsk_status==="CL"||item.hsk_status==="OS"||item.hsk_status==="OO"||item.hsk_status==="TU")){

            }else{
                RoomsViewArr.push(item)
            }
        })

        this.setState({
            RoomsViewArr:RoomsViewArr,
        })
    }

    onRequestClose(){
        this.setState({
            moreOperateModal: false,
        })
    }

    _renderItem = ({ item }) => {
        let datasource = this.state.RoomsViewArr;
        return(
            <View style={styles.roomDiskBox}>
                {
                    datasource.map((item, index) => {
                        let menu = "false";
                        if(this.state.floor === item.floor){
                            menu="false"
                        }else{
                            menu="true"
                        }
                        this.state.floor = item.floor;
                        return (
                            this._renderRoomsView(item, index,menu)
                        );

                    })
                }
            </View>
        )
    };

    //房态盘循环
    _renderRoomsView(item, index,menu){
        let _this = this;
        let returnHtml;
        let menuHtml = (
            <View key={item.floor} style={styles.cellFloorView}>
                <Text style={styles.cellFloorText}>
                    {item.floor+'层'}
                </Text>
                <TouchableOpacity  activeOpacity={1}
                                     onPress={() => {
                                         let aaa = 1;
                                         let multiCheckRooms = this.state.multiCheckRooms
                                         this.state.RoomsViewArr.map((ii, index) => {
                                             if(ii.floor === item.floor && !multiCheckRooms[ii.room]){
                                                 aaa = 0;
                                                 multiCheckRooms[ii.room] = item;
                                             }
                                         });
                                         if(aaa===1){
                                             for(let ever in multiCheckRooms) {
                                                 if(multiCheckRooms[ever].floor === item.floor){
                                                     delete multiCheckRooms[ever];
                                                 }
                                             }
                                         }
                                         this.setState({
                                             multiCheckRooms:multiCheckRooms,
                                         })
                                     }}
                >
                    <Text style={styles.cellFloorBtn}>
                        {
                            (_this.state.multiCheck) && (
                                this.ifFloorCheck(item.floor)
                            )
                        }
                    </Text>
                </TouchableOpacity>
            </View>
        );
        let roomHtml = (<TouchableHighlight  key={index} activeOpacity={0.9}

                                             onPress={() => {
                                                 if(_this.state.multiCheck){
                                                     let multiCheckRooms = _this.state.multiCheckRooms
                                                     if(multiCheckRooms[item.room]){//则包含该元素
                                                         delete multiCheckRooms[item.room]
                                                     }else{//不包含该元素
                                                         multiCheckRooms[item.room] = item;
                                                     }
                                                     _this.setState({
                                                         multiCheckRooms:multiCheckRooms,
                                                     })
                                                 }else{
                                                     // this.props.navigation.navigate('RoomStatusScreen',{room:item.room,button:'no',orderid:'',callBack:()=>{
                                                     //
                                                     // }});
                                                     let authority = '清洁人';
                                                     if(item.status==="完成清洁"){
                                                         authority = '检查人';
                                                     }
                                                     this.props.navigation.navigate('orderInfo',{room:item.room,hsk_status:item.hsk_status,qty:item.qty,button:'yes',authority:authority,orderid:'',callBack:()=>{

                                                     }});
                                                 }
                                             }}

                                             onLongPress={()=>{
                                                 let multiCheckRooms = {};
                                                 multiCheckRooms[item.room] = item;
                                                 _this.setState({
                                                     multiCheckRooms:multiCheckRooms,
                                                     multiCheck:true,
                                                 })
                                             }}
        >
            <View style={[styles.cellView,{backgroundColor:item.synbcolor}]}>
                <View style={styles.cellRoomDiskView}>
                    <View style={{flex: 1,flexDirection:'row'}}>
                        <View style={styles.cellLeftView}>
                            <View style={styles.cellLeftTopView}>
                                <Text style={[styles.cellLeftTopText,{color:item.syntcolor}]}>
                                    {item.room}
                                    {
                                        (item.connecting!==""&&"undefined"!==typeof(item.connecting))&&(<FontAwesome name={'code-fork'} size={16} style={{color: 'blue'}}/>)
                                    }
                                </Text>
                            </View>
                            {/*<View style={styles.cellLeftMidView}>
                            <Text style={[styles.cellLeftMidText,{color:item.syntcolor}]}>
                                {item.rmtype_c}
                            </Text>
                        </View>*/}
                        </View>
                        <View style={styles.cellRightView}>
                            <View style={styles.cellRightIconView}>
                                {_this.getIcon(item)}
                            </View>
                        </View>
                    </View>

                    <View style={{flex: 1,flexDirection:'row'}}>
                        <View style={styles.cellBottomView}>
                            <Text style={[styles.cellRightBottomText,{color:item.syntcolor}]}>
                                {item.gname}
                            </Text>
                        </View>
                        <View style={styles.cellBottomRightView}>
                            {
                                (_this.state.multiCheck) && (
                                    (_this.state.multiCheckRooms[item.room])
                                        ?
                                        (
                                            <Image style={{width: 18, height: 18}} source={require('../../../resource/login/yixuan.png')}/>
                                        )
                                        :
                                        (
                                            <Image style={{width: 18, height: 18}} source={require('../../../resource/login/weixuan.png')}/>
                                        )
                                )

                            }
                        </View>
                    </View>
                </View>
            </View>
        </TouchableHighlight >);

        if(menu==="true"){
            returnHtml = [menuHtml,roomHtml]
        }else{
            returnHtml = roomHtml
        }

        return(
            returnHtml
        )
    };

    ifFloorCheck(floor){
        let icon = (<Image style={{width: 20, height: 20}} source={require('../../../resource/login/quanxuan.png')}/>);
        this.state.RoomsViewArr.map((item, index) => {
            if(item.floor === floor && !this.state.multiCheckRooms[item.room]){
                icon = (<Image style={{width: 20, height: 20}} source={require('../../../resource/login/weixuan1.png')}/>);
            }
        });
        return icon;
    }

    //下拉刷新,更改状态，重新获取数据
    _onRefresh(){
        this.setState({
            refreshing:true,
        },()=>{
            let {dispatch} = this.props;

            let str = this.state.roomSearchStr;
            dispatch(RetrieveRoomsViewAs(JSON.stringify(str)));
        });
    }

    _renderFooter=()=>{
        return (
            <View style={{height:30,alignItems:'center',justifyContent:'flex-start',}}>
                <Text style={{color:'#999999',fontSize:14,marginTop:5,marginBottom:5,}}>
                    没有更多数据了
                </Text>
            </View>
        );
    }

    _onEndReached=()=>{
        return ;
    }

    getIcon=(item)=>{
        // console.log(JSON.stringify(item))
        return (
            <View style={{flexDirection: 'row',alignItems:"flex-end"}}>
                <Text>
                    {
                        (item.Skip.toString() === '1'&&this.ifShowIcon('skip'))&&(<Image style={{width:10,height:18}}  source={{uri: ''}} />)
                    }
                    {
                        (item.Sleep.toString() === '1'&&this.ifShowIcon('sleep'))&&(<Image style={{width:11,height:18}}  source={{uri: ''}} />)
                    }
                    {
                        (item.CheckedIn.toString() === '1'&&this.ifShowIcon('checkedin'))&&(<Image style={{width:18,height:18}}  source={{uri: ''}} />)
                    }
                    {
                        (item.OUTHouse.toString() === '1'&&this.ifShowIcon('outhouse'))&&(<Image style={{width:18,height:18}}  source={{uri: ''}} />)
                    }
                    {
                        (item.ishour.toString() ==='1'&&this.ifShowIcon('ishour'))&&(<AntDesign name={'clockcircleo'} size={16} style={{color: 'blue'}}/>)
                    }
                    {
                        (item.ishour.toString() ==='2'&&this.ifShowIcon('ishour'))&&(<AntDesign name={'clockcircleo'} size={16} style={{color: 'red'}}/>)
                    }
                    {
                        (item.ismorning.toString() ==='1')&&(<Feather name={'moon'} size={16} style={{color: 'red'}}/>)
                    }
                    {
                        (item.Depaturs.toString() === '1'&&this.ifShowIcon('depaturs'))&&(<FontAwesome name={'arrow-right'} size={16} style={{color: 'purple'}}/>)
                    }
                    {
                        (item.shared.toString() === '1'&&this.ifShowIcon('shared'))&&(<Image style={{width:13,height:18}}  source={{uri: ''}} />)
                    }
                    {
                        (item.O_Arrival.toString() === '1'&&this.ifShowIcon('o_arrival'))&&(<Image style={{width:13,height:18}}  source={{uri: ''}} />)
                    }
                    {
                        (item.ass !== ''&&item.ass.indexOf("选房占房")>-1&&this.ifShowIcon('ass'))&&(<FontAwesome name={'unlock'} size={16} style={{color: 'red'}}/>)
                    }
                    {
                        (item.ass !== ''&&item.ass.indexOf("选房占房")===-1&&this.ifShowIcon('ass'))&&(<FontAwesome name={'lock'} size={16} style={{color: '#69aa46'}}/>)
                    }
                    {
                        ((Number(item.V_Arrival)+Number(item.O_Arrival)) >0)&&(<FontAwesome name={'arrow-left'} size={16} style={{color: '#69aa46'}}/>)
                    }
                    {
                        (item.F_Arrival === '1'&&this.ifShowIcon('f_arrival'))&&(<FontAwesome name={'chevron-left'} size={16} style={{color: '#69aa46'}}/>)
                    }
                    {
                        (item.vip!=="")&&(<FontAwesome name={'vimeo'} size={16} style={{color: 'red'}}/>)
                    }
                </Text>
            </View>
        )
    };

    ifShowIcon(item){
        let ftpnoicoArr = this.state.ftpnoicoArr;
        if(ftpnoicoArr.indexOf(item)<0){
            return true;
        }else{
            return false;
        }
    }

    getMultiCheckRoomsLength(){
        let length = 0;
        for(let ever in this.state.multiCheckRooms) {
            length++;
        }
        return length;
    }

    //多选按钮
    multiBtn(){
        let {dispatch} = this.props;
        return (
            <View  style={{width:SCREEN_WIDTH,flexDirection: 'row',backgroundColor: '#f9f9f9'}}>
                <View style={styles.multiBtn}>
                    <View style={styles.cellRight}>
                        <View style={styles.cellRightTop}>
                            <Text  style={styles.multiBtnText}>
                                {
                                    (this.state.multiCheck)&&('已选：'+this.getMultiCheckRoomsLength())
                                }
                            </Text>
                        </View>
                    </View>
                </View>

                <TouchableOpacity activeOpacity={0.9} onPress={()=>{
                    let multiCheckRooms = {};
                    this.state.RoomsViewArr.map((item, index) => {
                        multiCheckRooms[item.room] = item;
                    })
                    this.setState({
                        multiCheckRooms:multiCheckRooms
                    })
                }}>
                    <View style={styles.multiBtn}>
                        <View style={styles.cellRight}>
                            <View style={styles.cellRightTop}>
                                <Text  style={styles.multiBtnText}>
                                    全选
                                </Text>
                            </View>
                        </View>
                    </View>
                </TouchableOpacity>
                <TouchableOpacity activeOpacity={0.9} onPress={()=>{
                    let multiCheckRooms = {};
                    this.setState({
                        multiCheckRooms:multiCheckRooms
                    })
                }}>
                    <View style={styles.multiBtn}>
                        <View style={styles.cellRight}>
                            <View style={styles.cellRightTop}>
                                <Text  style={styles.multiBtnText}>
                                    全不选
                                </Text>
                            </View>
                        </View>
                    </View>
                </TouchableOpacity>

                {/*领取*/}
                <TouchableOpacity activeOpacity={0.9} onPress={()=>{
                    let data = [];
                    let userid = "";
                    User.getUser(user => {
                        userid = user.userid;
                        for(let ever in this.state.multiCheckRooms) {
                            let item = this.state.multiCheckRooms[ever];
                            data.push({"room":item.room,"wuserid":userid,"iuserid":userid,"qty":item.qty,"wtype":item.wtype})
                        }
                        let str = {"data":data};
                        console.log(JSON.stringify(str));
                        dispatch(orderSweepSave(JSON.stringify(str)));
                    });

                }}>
                    <View style={styles.multiBtn}>
                        <View style={styles.cellRight}>
                            <View style={styles.cellRightTop}>
                                <Text  style={styles.multiBtnText}>
                                    领取
                                </Text>
                            </View>
                        </View>
                    </View>
                </TouchableOpacity>

                {/*关闭*/}
                <TouchableOpacity activeOpacity={0.9} onPress={()=>{
                    this.setState({
                        multiCheckRooms:{},
                        multiCheck:false,
                    })
                }}>
                    <View style={styles.multiBackBtn}>
                        <Text>
                            {/*<AntDesign name={'sync'} size={18} style={{color: '#6b6b6b'}}/>*/}
                            <Image style={{width: 20, height: 20}} source={require('../../../resource/login/tuichu.png')}/>
                        </Text>
                    </View>
                </TouchableOpacity>
            </View>
        )
    }

    //筛选条件View
    searchTitle(){
        let {dispatch} = this.props;

        return (
            <View style={{flexDirection: 'row',borderBottomWidth: 1,borderColor:COLOR_GRAY_LINE}}>
                <TouchableOpacity activeOpacity={0.8} onPress={()=>{

                }}>
                    <View style={styles.cellBoxLeft}>
                        <View style={styles.cellRight}>
                            <View style={styles.cellRightTop}>
                                <Text style={styles.cellTitleText}>
                                    开房率:{this.state.INHouse.toString()}/{this.state.RoomsViewArr.length}
                                </Text>
                            </View>
                        </View>
                    </View>
                </TouchableOpacity>

                <TouchableOpacity activeOpacity={0.8} onPress={() => {
                    let condition = ["building","floor","rmtype","roomService"];
                    let selectValue = this.state.selectValue;
                    this.props.navigation.navigate('FiltersScreen',{"searchCode":condition,"dataBack":(selectValue)=>{
                            Object.assign(this.state.selectValue, selectValue);
                            Object.assign(this.state.roomSearchStr.where, selectValue);

                            let text = '';
                            if(typeof(this.state.selectValue["building_c"])!=="undefined" &&this.state.selectValue["building_c"]!=="全部"){
                                text += this.state.selectValue["building_c"]+',';
                            }
                            if(typeof(this.state.selectValue["rmtype_c"])!=="undefined" &&this.state.selectValue["rmtype_c"]!=="全部"){
                                text += this.state.selectValue["rmtype_c"]+',';
                            }
                            if(typeof(this.state.selectValue["floor_c"])!=="undefined" &&this.state.selectValue["floor_c"]!=="全部"){
                                text += this.state.selectValue["floor_c"]+',';
                            }
                            if(typeof(this.state.selectValue["roomService_c"])!=="undefined" &&this.state.selectValue["roomService_c"]!=="所有房间"){
                                text += this.state.selectValue["roomService_c"]+',';
                            }
                            if(text===""){
                                text = '查询条件'
                            }else{
                                text = text.slice(0,text.length-1)
                            }
                            this.setState({
                                searchText: text,
                            });

                            let str = this.state.roomSearchStr;
                            let selectValueChange = JSON.parse(JSON.stringify(this.state.selectValue));

                            if(this.state.selectValue["roomService_c"]==="所有房间"){
                                str.wherestatus = {"All":"1"}
                            }else{
                                delete selectValueChange.roomService["seq"];
                                delete selectValueChange.roomService["total"];
                                delete selectValueChange.roomService["c_sort"];
                                str.wherestatus =selectValueChange.roomService;
                                delete str.where["roomService"];
                            }
                            dispatch(RetrieveRoomsViewAs(JSON.stringify(str)));
                        },"selectValue":selectValue});
                }}>
                    <View style={styles.cellBoxCenter}>
                        <View style={styles.cellRight}>
                            <View style={styles.cellRightTop}>
                                {
                                    this.state.searchText==="查询条件"&&( <Text style={styles.cellTitleText}>
                                        <AntDesign name={'search1'} size={18} style={{color: '#6b6b6b'}}/>
                                    </Text>)
                                }

                                <Text style={styles.cellTitleText}>
                                    {this.state.searchText}
                                </Text>
                            </View>
                        </View>
                    </View>
                </TouchableOpacity>

                <TouchableOpacity activeOpacity={0.8} onPress={()=>{
                    this.setState({
                        moreOperateModal:true,
                    })
                }}>
                    <View style={styles.cellBoxRight}>
                        <View style={styles.cellRight}>
                            <View style={styles.cellRightTop}>
                                    <Image style={{width: 20, height: 20}} source={require('../../../resource/login/shengluehao.png')}/>
                            </View>
                        </View>
                    </View>
                </TouchableOpacity>

            </View>
        )
    }

}

const props = state => {
    return {
        onRetrieveRoomsView: state.onRetrieveRoomsView,
        onReservationDefault: state.onReservationDefault,
        onOrderSweepSave:state.onOrderSweepSave,
    }
};

export default allOrderScreen = connect(props)(allOrderScreen);
